//
//  PywLoginGameView.m
//  PywSdk
//
//  Created by Jade on 4/7/16.
//  Copyright © 2016 zero. All rights reserved.
//

#import "PywLoginGameView.h"
#import "PywInputTF.h"
#import "PywLoginDataSource.h"
#import "PywMasonry.h"
#import "UIImage+Pyw.h"
#import "PywLoginTopView.h"
#import "PywInputView.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PywAccount.h"
#import "PywPlatformMain.h"
#import "PywIAPHelper.h"
#import "PywLoginAccountApi.h"
#import "PywNewAccountApi.h"
#import "PywCPNotifications.h"
#import "PywSdk+login.h"
#import "PywAppInfo.h"

#import "PywUploadAccountLoginManager.h"
#import "PywRealNameAuthManager.h"
@interface PywLoginGameView()<UITextFieldDelegate>

@property (nonatomic,strong) PywLoginTopView *topView;
@property (nonatomic,strong) UILabel *titleLabel;
@property (nonatomic,strong) PywInputView *accountInputTF;
@property (nonatomic,strong) UITableView *accountListTable;
@property (nonatomic,strong) UIButton *loginButton;
@property (nonatomic,strong) UIButton *newAccountButton;
@property (nonatomic,strong) UIButton *selectAccontButton;
@property (nonatomic,strong) UIButton *backButton;

@property (nonatomic,strong) NSMutableArray *accountList;
@property (nonatomic,strong) PywLoginDataSource *dataSource;

@property (nonatomic,assign) BOOL isNewGameLogin;//是否新建账号后新建账号

@property (nonatomic,strong) PywLoginAccountApi *loginAccoutApi;
@property (nonatomic,strong) PywNewAccountApi *accountNewApi;
@end
@implementation PywLoginGameView

- (instancetype)initWithAccountList:(NSArray *)accountList
{
    self = [super init];
    if (self) {
        self.accountList = [NSMutableArray arrayWithArray:accountList];
        [self setUp];
        NSLog(@"进入二级登录页面");
    }
    return self;
}
- (void)dealloc
{
    NSLog(@"退出二级登录页面");
}

#pragma mark - setUp

- (void)setUp
{
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius = 20.f;
    self.layer.masksToBounds = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?NO:YES;
    self.alpha = 0;
    
    [self addSubview:self.topView];
    if ([PywAppInfo sharedAppInfo].appType == AppTypeFQ) {
        [self addSubview:self.backButton];
    }else {
        [self.topView addSubview:self.backButton];
    }
    
    [self addSubview:self.titleLabel];
    [self addSubview:self.accountInputTF];
    [self addSubview:self.loginButton];
    [self addSubview:self.newAccountButton];
    [self addConstraints];
    
    if (self.accountList.count == 0) {
         [self requestNewLoginGameAccount];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    /**
     *  Table 的约束
     */
    if (!CGRectEqualToRect(self.frame, CGRectZero)) {
        if (!_accountListTable) {
            [self addSubview:self.accountListTable];
            __weak typeof(self) weakSelf = self;
            [self.accountListTable mas_makeConstraints :^(PywMASConstraintMaker *make) {
                make.centerX.offset(0);
                make.top.mas_equalTo(weakSelf.accountInputTF.mas_bottom);
                make.width.mas_equalTo(weakSelf.accountInputTF.mas_width);
                make.height.mas_equalTo(0);
            }];
        }
        
    }
}

/**
 *  添加约束
 */
- (void)addConstraints
{
    __weak typeof(self) weakSelf = self;
    [self.topView mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.mas_left);
        make.top.mas_equalTo(weakSelf.mas_top);
        make.right.mas_equalTo(weakSelf.mas_right);
        CGFloat height  = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?0.1:0.17;
        make.height.mas_equalTo(weakSelf.mas_height).multipliedBy(height);
    }];
    [self.titleLabel mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.width.mas_equalTo(weakSelf.mas_width).multipliedBy(0.85);
        make.height.mas_equalTo(weakSelf.mas_height).multipliedBy(0.15);
        make.top.mas_equalTo(weakSelf.topView.mas_bottom).offset(10);
    }];
    
    [self.accountInputTF mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.mas_equalTo(weakSelf.titleLabel.mas_bottom).offset(0);
        make.width.mas_equalTo(weakSelf.mas_width).multipliedBy(0.9);
        make.height.mas_equalTo(weakSelf.mas_height).multipliedBy(0.15);
    }];
    
    [self.loginButton mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.width.mas_equalTo(weakSelf.accountInputTF);
        make.height.mas_equalTo(40);
        make.top.mas_equalTo(weakSelf.accountInputTF.mas_bottom).offset(15);
    }];
    
    
    [self.backButton mas_makeConstraints:^(PywMASConstraintMaker *make) {
        if ([PywAppInfo sharedAppInfo].appType == AppTypeFQ) {
            make.left.equalTo(weakSelf.loginButton.mas_left);
            make.top.equalTo(weakSelf.loginButton.mas_bottom).offset(20);
        }else {
            make.centerY.equalTo(weakSelf.topView.mas_centerY);
            make.left.mas_equalTo(10);
            make.width.height.mas_equalTo(33);
        }
    }];
    
    [self.newAccountButton mas_makeConstraints:^(PywMASConstraintMaker *make) {
        if ([PywAppInfo sharedAppInfo].appType == AppTypeFQ) {
            make.right.equalTo(weakSelf.loginButton.mas_right);
            make.top.mas_equalTo(weakSelf.loginButton.mas_bottom).offset(20);
        }else {
            make.centerX.offset(0);
            make.height.width.mas_equalTo(weakSelf.loginButton);
            make.top.mas_equalTo(weakSelf.loginButton.mas_bottom).offset(10);
        }
    }];
}


#pragma mark - setter
- (PywLoginTopView *)topView
{
    if (!_topView) {
        _topView = [[PywLoginTopView alloc] init];
    }
    return _topView;
}

- (UIButton *)backButton
{
    if (!_backButton) {
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        if ([PywAppInfo sharedAppInfo].appType == AppTypeFQ) {
            [_backButton.titleLabel setFont:[UIFont systemFontOfSize:13.f]];
            [_backButton setTitleColor:UIColorFromRGB(0xFF888888)
                              forState:UIControlStateNormal];
            [_backButton setTitleColor:[UIColor blueColor]
                              forState:UIControlStateHighlighted];
            [_backButton setTitle:@"< 返回登录"
                         forState:UIControlStateNormal];
        }else {
            [_backButton setImage:[UIImage imageWithName:@"icon_return_normal"]
                         forState:UIControlStateNormal];
        }
        
        [_backButton addTarget:self
                        action:@selector(handleReturnback:)
              forControlEvents:UIControlEventTouchUpInside];
        [_backButton setAccessibilityIdentifier:@"back_login"];
    }
    return _backButton;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        
        _titleLabel = [UILabel new];
        _titleLabel.textColor = [UIColor colorWithRed:87/255.f green:87/255.f blue:87/255.f alpha:1.f];
        _titleLabel.font = [UIFont systemFontOfSize:11.f];
        _titleLabel.text = [NSString stringWithFormat: @"欢迎登录，%@，请选择游戏账号",[PywPlatformMain sharedPlatformMain].passport];
    }
    return _titleLabel;
}

- (PywInputView *)accountInputTF
{
    if (!_accountInputTF) {
        _accountInputTF = [[PywInputView alloc] init];
        _accountInputTF.delegate = self;
        _accountInputTF.placeholder = @"请输入游戏账号";
        _accountInputTF.rightView = self.selectAccontButton;
        _accountInputTF.leftView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"icon_user_normal"]];
        [_accountInputTF addTarget:self
                            action:@selector(accountTextFieldChange:)
                  forControlEvents:UIControlEventEditingDidBegin];
        if (self.accountList.count > 0) {
            PywAccount *account = self.accountList[0];
            _accountInputTF.text = account.account;
        }
        
        UIView *overView = [[UIView alloc] init];
        [_accountInputTF addSubview:overView];
        [overView mas_makeConstraints:^(PywMASConstraintMaker *make) {
            make.height.left.bottom.equalTo(_accountInputTF);
            make.width.equalTo(_accountInputTF).offset(-30);
        }];
    }
    return _accountInputTF;
}

- (UITableView *)accountListTable
{
    if (!_accountListTable) {
        _accountListTable = [[UITableView alloc] init];
        _accountListTable.layer.borderWidth = 1;
        _accountListTable.layer.borderColor = [UIColor colorWithRed:237/255.f
                                                              green:237/255.f
                                                               blue:237/255.f
                                                              alpha:1.f].CGColor;
        _accountListTable.tableFooterView = [[UIView alloc] init];
        _accountListTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _accountListTable.dataSource = self.dataSource;
        _accountListTable.delegate = self.dataSource;
    }
    return _accountListTable;
}

- (UIButton *)loginButton{
    
    if (!_loginButton) {
        
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginButton.layer.cornerRadius = 20;
        [_loginButton setTitle:@"进入游戏" forState:UIControlStateNormal];
        _loginButton.backgroundColor = [UIColor colorWithRed:255/255.f
                                                       green:188/255.f
                                                        blue:0/255.f
                                                       alpha:1.f];
        [_loginButton setTitleColor:[UIColor whiteColor]
                           forState:UIControlStateNormal];
        [_loginButton setTitleColor:[UIColor blackColor]
                           forState:UIControlStateHighlighted];
        [_loginButton addTarget:self
                         action:@selector(selectLoginButton:)
               forControlEvents:UIControlEventTouchUpInside];
        [_loginButton setAccessibilityIdentifier:@"login_gotogame"];
    }
    return _loginButton;
}

- (UIButton *)newAccountButton
{
    if (!_newAccountButton) {
        _newAccountButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _newAccountButton.layer.cornerRadius = 18;
        if ([PywAppInfo sharedAppInfo].appType == AppTypeFQ) {
            [_newAccountButton.titleLabel setFont:[UIFont systemFontOfSize:13.f]];
            [_newAccountButton setTitle:@"+ 新建游戏账号"
                               forState:UIControlStateNormal];
            [_newAccountButton setTitleColor:UIColorFromRGB(0xFFFFAA00)
                                    forState:UIControlStateNormal];
            [_newAccountButton setTitleColor:[UIColor blueColor]
                                    forState:UIControlStateHighlighted];
        }else {
            [_newAccountButton setTitle:@"新建游戏账号"
                               forState:UIControlStateNormal];
            [_newAccountButton setTitleColor:[UIColor colorWithRed:87/255.f green:87/255.f blue:87/255.f alpha:1.f]
                                    forState:UIControlStateNormal];
            _newAccountButton.backgroundColor = [UIColor whiteColor];
            [_newAccountButton setTitleColor:[UIColor blueColor]
                                    forState:UIControlStateHighlighted];
            _newAccountButton.layer.borderWidth = 1;
            _newAccountButton.layer.borderColor = [UIColor colorWithRed:233/255.f green:233/255.f blue:233/255.f alpha:1.f].CGColor;
        }
        
        [_newAccountButton addTarget:self
                              action:@selector(selectNewAccountButton:)
                    forControlEvents:UIControlEventTouchUpInside];
        [_newAccountButton setAccessibilityIdentifier:@"login_newaccount"];
        
    }
    return _newAccountButton;
}


- (UIButton *)selectAccontButton{
    
    if (!_selectAccontButton) {
        
        _selectAccontButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _selectAccontButton.frame = CGRectMake(0, 0, 25, 25);
        [_selectAccontButton setImage:[UIImage imageWithName:@"icon_login_drop_normal"]
                              forState:UIControlStateNormal];
        [_selectAccontButton addTarget:self
                                action:@selector(selectAccontButton:)
                      forControlEvents:UIControlEventTouchUpInside];
    }
    return _selectAccontButton;
}

- (PywLoginDataSource *)dataSource
{
    if (!_dataSource) {
        __weak typeof(self) weakSelf = self;
        NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:self.accountList.count];
        for (PywAccount *account in self.accountList) {
            [array addObject:account.account];
        }
        if ([PywPlatformMain sharedPlatformMain].changeAccount.length > 0) {
            for (NSInteger i = 0; i < array.count; i ++) {
                NSString *userName = [array objectAtIndex:i];
                if ([userName isEqualToString:[PywPlatformMain sharedPlatformMain].changeAccount]) {
                    [array exchangeObjectAtIndex:i withObjectAtIndex:0];
                    self.accountInputTF.text = userName;
                    break;
                }
            }
        }
        
        
        _dataSource = [PywLoginDataSource createTableDataSourceWithDataList:array isEdit:NO didSelectRow:^(NSIndexPath *indexPath) {
            [weakSelf endEditing:YES];
            PywAccount *account = weakSelf.accountList[indexPath.row];
            weakSelf.accountInputTF.text = account.account;
            [weakSelf hideTable];
            [self animationRoatateDropArrow:weakSelf.selectAccontButton.selected];
        }];
    }
    return _dataSource;
}


#pragma mark - Action Method
/**
 *  返回登录页面
 *
 *  @param sender <#sender description#>
 */
- (void)handleReturnback:(UIButton *)sender
{
    if (self.returnbackLoginCompletion) {
        self.returnbackLoginCompletion(self);
    }
}

/**
 *  输入文本
 *
 *  @param textFiled <#textFiled description#>
 */
- (void)accountTextFieldChange:(PywInputTF *)textFiled
{
    [self hideTable];
}

/**
 *  点击进入游戏
 *
 *  @param sender <#sender description#>
 */
- (void)selectLoginButton:(UIButton *)sender
{
    [self endEditing:YES];
    [self hideTable];
    NSString *account = [self.accountInputTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (account.length == 0) {
        [PywMBProgressHUD showError:@"请输入账号！" toView:[UIApplication sharedApplication].keyWindow];
        return;
    }
    [self requestAccountLoginNoPwd:account];
}

/**
 *  新建游戏账号
 *
 *  @param sender <#sender description#>
 */
- (void)selectNewAccountButton:(UIButton *)sender
{
    [self endEditing:YES];
    [self hideTable];
    [self requestNewLoginGameAccount];
}


/**
 *  选择游戏账号列表
 *
 *  @param sender <#sender description#>
 */
- (void)selectAccontButton:(UIButton *)sender
{
    [self endEditing:YES];
    [self animationRoatateDropArrow:sender.selected];
    sender.selected = !sender.selected;
    sender.selected?[self showTable]:[self hideTable];
}


#pragma mark - Public
/**
 *  添加到父视图
 *
 *  @param superView   superView
 *  @param accountList superView
 */
- (void)add2SuperView:(UIView *)superView
{
    [superView addSubview:self];
    [self mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.center.offset(0);
        NSInteger viewWidth = [UIScreen mainScreen].bounds.size.width >
        [UIScreen mainScreen].bounds.size.height ?
        [UIScreen mainScreen].bounds.size.height :
        [UIScreen mainScreen].bounds.size.width;
        viewWidth = MIN(viewWidth, 500);
        make.width.equalTo(@(viewWidth * 0.85));
        if (viewWidth%320 == 0 || viewWidth%480 == 0) {
            CGFloat height  = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?0.65:0.75;
            make.height.equalTo(@(viewWidth * height));
        }else {
            CGFloat height  = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?0.58:0.65;
            make.height.equalTo(@(viewWidth * height));
        }
    }];
    
}


#pragma mark - Request
/**
 *  新建游戏账号
 */
- (void)requestNewLoginGameAccount
{
    self.accountNewApi = [PywNewAccountApi manager];
    WEAK_SELF;
    [self.accountNewApi requestNewAccount:^(NSString *status, id anyObjct) {
        NSDictionary *dict = (NSDictionary *)anyObjct;
        STRONG_SELF(weakSelf);
        [PywPlatformMain sharedPlatformMain].uid = [NSString stringWithFormat:@"%@",dict[@"data"][@"cp_uid"]];
        [PywPlatformMain sharedPlatformMain].account = [NSString stringWithFormat:@"%@",dict[@"data"][@"account"]];
        [PywPlatformMain sharedPlatformMain].token = [NSString stringWithFormat:@"%@",dict[@"data"][@"token"]];
        
        [[PywIAPHelper manager] checkLocalApplePay];
        [PywMBProgressHUD showError:@"游戏账号新建成功"];
        [strongSelf loginSuccess];
    } fail:^(NSError *error) {
        [PywMBProgressHUD showError:@"注册失败,请重新注册"];
    }];
    
}

/**
 *  免密码登录
 */
- (void)requestAccountLoginNoPwd:(NSString *)account
{
    self.loginAccoutApi = [PywLoginAccountApi manager];
    WEAK_SELF;
    [self.loginAccoutApi requestLoginAccount:account success:^(NSString *status, id anyObjct) {
        STRONG_SELF(weakSelf);
        [PywMBProgressHUD showSuccess:@"已登录"];
        [strongSelf loginSuccess];
    } fail:^(NSError *error) {
        switch (error.code) {
            case 1005:
            {
                [PywMBProgressHUD showError:@"游戏账号错误"];
            }
                break;
            default:
            {
                [PywMBProgressHUD showError:@"登录失败，请重新登录"];
            }
                break;
        }
    }];
}

/**
 *  登录成功
 */
- (void)loginSuccess
{
    if (self.accountLoginCompletion) {
        self.accountLoginCompletion(self);
    }
    
    // 关闭时才发送登录完成的通知
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    // 发送登录完成的通知
    [dict setObject:[NSNumber numberWithInt:PYW_LOGIN_STATE_SUCCESS] forKey:@"result"];
    [dict setObject:@"登录成功" forKey:@"info"];
    [dict setObject:[PywPlatformMain sharedPlatformMain].account forKey:@"account"];
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:kPywCPLoginNotification object:nil userInfo:dict];
    
    // 登录成功，保存当前账号登录时间,并查询是否上传登录时长
    [[PywUploadAccountLoginManager manager] uploadAccountLoginTimeLong];
    
    // Modal出“实名认证”控制器，加载Web端实名制认证
    [[PywRealNameAuthManager manager] showRealNameAuthViewController];
}


#pragma mark - UITextFieldDelegate

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.accountInputTF.text = textField.text;
}

#pragma mark - Private

/**
 *  旋转选择账号列表按钮
 *
 *  @param isRotate <#isRotate description#>
 */
- (void)animationRoatateDropArrow:(BOOL)isRotate
{
    CATransform3D tranfrom = isRotate?CATransform3DIdentity:CATransform3DMakeRotation(M_PI, 0, 0, 1);
    [UIView animateWithDuration:.2f
                     animations:^{
                         _selectAccontButton.layer.transform = tranfrom;
                     } completion:^(BOOL finished) {
                         
                     }];
}
/**
 *  显示Table
 *
 */
- (void)showTable
{
    __weak typeof(self) weakSelf = self;
    CGRect accountFrame = self.accountListTable.frame;
    accountFrame.size.height = 88.f;
    [UIView animateWithDuration:.2f
                          delay:0.f
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         weakSelf.accountListTable.frame = accountFrame;
                     } completion:^(BOOL finished) {
                         weakSelf.selectAccontButton.selected = YES;
                     }];
    
}

/**
 *  隐藏Table
 */
- (void)hideTable
{
    __weak typeof(self) weakSelf = self;
    CGRect accountFrame = self.accountListTable.frame;
    accountFrame.size.height = 0.f;
    [UIView animateWithDuration:.2f
                          delay:0.f
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         weakSelf.accountListTable.frame = accountFrame;
                     } completion:^(BOOL finished) {
                         weakSelf.selectAccontButton.selected = NO;
                     }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self endEditing:YES];
}


@end
